<!-- 库存管理 -->
<template>
  <div class="stock_manager">
    <el-main class="base_main_content">
      <div class="base_screen_header">
        <span></span>
        <el-form :inline="true" class="base_search_form" @submit.prevent>
          <!-- <el-form-item>
            <el-date-picker v-model="date" type="daterange" range-separator="~" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD" @change="searchDate" />
          </el-form-item> -->
          <el-form-item>
            <el-select v-model="base" @change="searchBase" placeholder="请选择基地" clearable>
              <el-option v-for="(item, index) in baseOptions" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="name" @keyup[native].enter="searchName" @change="searchName" placeholder="商品名称"
              :suffix-icon="Search" clearable />
          </el-form-item>
          <el-form-item>
            <el-input v-model="sku" @keyup[native].enter="searchSKU" @change="searchSKU" placeholder="SKU编码"
              :suffix-icon="Search" clearable />
          </el-form-item>
        </el-form>
      </div>

      <DataCollectTable :data="data" :total="total" :config="config" @operationsHander="opHander.receive" />

    </el-main>
    <el-dialog v-model="dialogVisible" title="库存变化" width="35%" top="30vh" class="base_dialog"
      @open="resetForm(inventoryFormRef)">
      <el-form ref="inventoryFormRef" :model="inventoryForm" :rules="inventoryRules" label-width="80px">
        <el-form-item label="变更类型" prop="type">
          <el-radio-group v-model="inventoryForm.type">
            <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="变更数量" prop="amount">
          <el-input v-model.number="inventoryForm.amount" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="inventoryForm.remark" type="textarea" clearable resize="none" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="stockChange(inventoryFormRef)">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import DataCollectTable from '@com/table/DataCollectTable.vue'
import { OP_KEY, OPERATIONS, COLUMN_TYPE, operationsHander } from "@com/table/tableOperations";
import { ref, reactive } from 'vue'
import { Search } from '@element-plus/icons-vue'
import useRoute from "@util/router";
import api from "@api/goodsStock"
import $ from "@util/base"
import { $msg } from '@/common/ui/msg';

const route = useRoute()

const baseOptions = ref([])
const total = ref(0)
const data = ref([])
const base = ref(route.query().base || '')
const name = ref(route.query().name || '')
const sku = ref(route.query().sku || '')

const dialogVisible = ref(false)

route.watchRouter("financestockmanager", () => {
  if ($.isNull(route.query().tab) || route.query().tab == "goods") {
    getData()
  }
})

const date = ref(route.query().date || []);
function searchDate(val) {
  route.replaceQuery("date", val);
}

const typeOptions = [{
  label: '增加',
  value: 1
}, {
  label: '减少',
  value: 2
}]
const inventoryFormRef = ref('')
const inventoryForm = reactive({
  type: null,
  amount: null,
  remark: null
})

const checkAmount = (rule, value, callback) => {
  if (value <= 0) {
    callback(new Error('不能小于0'))
  }
  return true
}
const inventoryRules = {
  type: [{
    required: true,
    message: '请选择变更类型',
    trigger: 'change',
  }],
  amount: [{
    required: true,
    message: '请输入变更数量',
    trigger: 'blur',
  }, {
    type: 'number',
    message: '请输入数字',
  }, { validator: checkAmount }]
}

const stockChange = (formEl) => {
  formEl.validate((valid, fields) => {
    if (valid) {
      if (stockChangeData != null) {
        api.stockChange({
          productCode: stockChangeData.productCode,
          skuCode: stockChangeData.skuCode,
          changeNum: inventoryForm.amount,
          changeFlag: inventoryForm.type,
          remark: inventoryForm.remark
        }, () => {
          $msg.succ("变更成功")
          dialogVisible.value = false
          formEl.resetFields()
          getData()
        })
      } else {
        $msg.error("请重新选择记录操作")
      }
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

function goodsOperations(data) {
  return [OPERATIONS.inventory]
}

const config = {
  showIndex: true,
  operations: null,
  column: [
    {
      label: '商品名称',
      prop: 'productName',
      type: COLUMN_TYPE.linkText,
      operationsKey: OPERATIONS.linkText,
    }, {
      label: '规格名称',
      prop: 'attrDetail',
      width: 180,
    }, {
      label: '规格编码',
      prop: 'skuCode',
      width: 150,
    }, {
      label: "成本价（元）",
      prop: "costPrice",
      type: COLUMN_TYPE.inputPrice,
      operationsKey: OPERATIONS.inputPrice,
      width: 120,
    }, {
      label: '归属基地',
      prop: 'shop',
      width: 150,
    }, {
      label: '当前库存',
      prop: 'stockNum',
      width: 140,
    }
    // , {
    //   label: '可用库存',
    //   prop: 'lockNum',
    //   width: 140,
    // }
  ]
}
var stockChangeData = null
const opHander = operationsHander()
opHander.install(OP_KEY.inventory, (data) => {
  stockChangeData = data
  dialogVisible.value = true
})
opHander.install(OP_KEY.inputPrice, (data) => {
  api.costUpdate(data.value, data.data.skuCode, () => {
    $msg.succ("修改成功");
  });
});
opHander.install(OP_KEY.linkText, (data) => {
  route.push({ name: 'goodsstockrecode', query: { sku: data.skuCode } })
});

function searchBase(val) {
  route.replaceQuery('base', val)
}
function searchName(val) {
  route.replaceQuery('name', val)
}
function searchSKU(val) {
  route.replaceQuery('sku', val)
}

getConfig()
function getConfig() {
  api.base(val => {
    baseOptions.value = val
  })
}

getData()

function getData() {
  let routeQuery = route.query()
  api.skuStock({
    skuCode: routeQuery.sku,
    shopCode: routeQuery.base,
    productName: routeQuery.name,
    date: routeQuery.date,
    page: routeQuery.p,
    size: routeQuery.s
  }, val => {
    data.value = val.itemList
    total.value = val.total
  })
}

function getExport() {
  let routeQuery = route.query()
  api.stockExport({
    skuCode: routeQuery.sku,
    shopCode: routeQuery.base,
    date: routeQuery.date,
    productName: routeQuery.name,
  }, val => {
    $.download(val.url, "库存列表导出")
  })
}


</script>

<style lang="scss"></style>